package cn.gok.springsecuritydemo01.service;

import cn.gok.springsecuritydemo01.dao.UserDAO;
import cn.gok.springsecuritydemo01.entity.User;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author: chen fan
 * @since: 2022/11/18 10:25
 * @description:
 */

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDAO userDAO;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);

        //先根据用户名查询出用户信息
        User user = userDAO.selectOne(queryWrapper);
        if ( user == null){
            throw new UsernameNotFoundException("用户不存在");
        }

        //构建用户的其他信息，比如权限列表， 是否锁定等等

        //添加权限集合
        user.setAuthorities(new ArrayList<GrantedAuthority>());



        //设置密码不加密， Spring Security 默认是对密码进行加密处理的
        user.setPassword( "{noop}" + user.getPassword());

        return user;
    }
}
